package com.wondertek.mist;

import java.net.URL;
import java.security.MessageDigest;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.cordova.api.LOG;

public class TrustHTTPS {

	private static char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E','F' };

	private static String[] TRUSTS = {
			//20151127
			// *.ecpic.com.cn 
			"03CF5BCF2FBCBF51C6A1E785BEF09BCAA38F1DE6",
			//20160927
			"6747B3FE4E0CB4759F788425BE0EDDB9C9C8C5D9",
			// *.cpic.com.cn
			"A8CCF9EF56BFF1E39534CF92F407786EB59F9168",
			//20160927
			"0E914E87A0678EE301217C4EE660130FA22FB9A3"
	};

	private static String getFingerprints(String httpsURL) throws Exception {
		final HttpsURLConnection con = (HttpsURLConnection) new URL(httpsURL).openConnection();
		SSLContext sc = SSLContext.getInstance("SSL");
		sc.init(null, new TrustManager[] { new X509TrustManager() {
			@Override
			public X509Certificate[] getAcceptedIssuers() {
				return new X509Certificate[] {};
			}

			@Override
			public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

			}

			@Override
			public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

			}
		} }, new java.security.SecureRandom());

		con.setSSLSocketFactory(sc.getSocketFactory());
		con.setHostnameVerifier(new HostnameVerifier() {

			@Override
			public boolean verify(String hostname, SSLSession session) {
				return true;
			}
		});
		con.setConnectTimeout(5000);
		con.connect();
		Certificate[] certs = con.getServerCertificates();
		MessageDigest md = MessageDigest.getInstance("SHA1");
		for (int i = 0; i < certs.length; i++) {
			md.update(certs[i].getEncoded());
		}

		return dumpHex(md.digest());
	}

	private static String dumpHex(byte[] data) {
		final int n = data.length;
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < n; i++) {
			sb.append(HEX_CHARS[(data[i] >> 4) & 0x0F]);
			sb.append(HEX_CHARS[data[i] & 0x0F]);
		}
		return sb.toString();
	}

	public static boolean trust(String url) {
		if (!url.startsWith("https")) {
			return true;
		}

		try {
			String fp = getFingerprints(url);
			for (String t : TRUSTS) {
				if (fp.equalsIgnoreCase(t)) {
					return true;
				}
			}
			LOG.i("HTTPS", fp);
			return false;
		} catch (Exception e) {
			e.printStackTrace();
			return true;
		}
	}
}
